var userService = require('../services/userService');
var messageUtil = require('../common/utils/messageUtil');
var cacheUtil = require('../common/utils/cacheUtil');
var toolUtil = require('../common/utils/toolUtil');
var mysqlUtil = require('../common/utils/mysqlUtil');
var inviteRecord = mongoose.model('invite_score_record');
var fs = require('fs');
var Users = mongoose.model('user');
var async = require('async');
var md5 = require('MD5');
var moment = require('moment');
var userDevice = mongoose.model('user_device_profile');
var appService = require('../services/appService');
var marketService = require('../services/marketService');
var Geetest = require('gt3-sdk');

var deviceLimit = 2;

/**
 * User sign up a user with the information:
 * userID/email/mobilePhone + password
 * The request content-type should be application/json
 */
exports.registerUser = function (req, res) {
    logger.debug('Registering a user...');
    var input = req.body;
    var clientId = input.clientId;

    var deviceId = req.params.deviceId;
    var type = req.cparams.type;
    var vcode = req.cparams.vcode;

    var key = 'app:user:device:register';

    redisClient.HGET(key, deviceId, function (err, value) {
        if (value == null || (type == 'android' && Number(vcode) < 107000) || (value != null && value.split(',').length < REGISTER_LIMIT)) {

            if ((input.userName != null || input.email != null || input.mobilePhone != null) && input.userPassword != null && input.verificationCode != null) {
                cacheUtil.cacheGet(input.mobilePhone, function (err, result) {
                    if (result != null && result == input.verificationCode) {
                        var password = md5(input.userPassword);
                        userService.registerService(input.userName, input.email, input.mobilePhone, password, clientId, function (err, user) {
                            if (err) {

                                var message = {
                                    "deviceId": req.params.deviceId,
                                    "mobilePhone": input.mobilePhone,
                                    "password": input.userPassword,
                                    "message": '用户名已被注册'
                                };
                                toolUtil.putMessageLoginOrRegisterLogMQ(message);

                                logger.error("Failed to register this user - " + err.message);
                                res.json(messageUtil.composeFailedMessage(req, '用户名已被注册'));
                            } else {
                                logger.debug("Succeeded to register a user! - " + user._id);
                                //获取token并缓冲
                                logger.info(user._id);
                                var token = toolUtil.generateAndCacheToken(user._id);
                                //返回消息
                                var registerUserData = {
                                    "_id": user._id,
                                    "huanxinUserName": user.huanxinUserName,
                                    "token": token,
                                    "firstLogin": user._doc.firstLogin,
                                    "appSetting": user.appSetting,
                                    "userType": user.userType,
                                    "vStatus": 0,
                                    "auth": [],
                                    "authenticationStatus": user.authenticationStatus
                                };
                                //userService.sendWelcomeNewsService(input.mobilePhone, function (err, result) {
                                //    if (err) {
                                //        logger.error('failed to send welcome news' + err.message);
                                //    }
                                //});
                                toolUtil.setUserByToken(token);
                                redisClient.sadd('u:all', user._id);
                                res.json(messageUtil.composeSucceededMessage(req, null, registerUserData));

                                //储存设置注册信息
                                redisClient.HSET(key, deviceId, value == null ? user._id + '' : value + ',' + user._id);
                            }
                        });
                    } else {
                        var message = {
                            "deviceId": req.params.deviceId,
                            "mobilePhone": input.mobilePhone,
                            "password": input.userPassword,
                            "message": '验证码错误'
                        };
                        toolUtil.putMessageLoginOrRegisterLogMQ(message);
                        logger.error("Failed to register user ! - invalid verification code!");
                        res.json(messageUtil.composeFailedMessage(req, '验证码错误'));
                    }
                })
            } else {
                logger.error("Failed to register user ! - You have to provide at least userID/email/mobilePhone and also password +  verificationCode for registration...!");
                res.json(messageUtil.composeFailedMessage(req, '请填写手机号、密码或验证码'));
            }
        } else {
            res.json(messageUtil.composeFailedMessage(req, '手机注册达到上限'))
        }
    });
};


exports.bindClientId = function (req, res) {
    var clientId = req.params.clientId;
    var token = req.params.token;
    var vcode = req.query.vcode;

    userService.bindClientIdService(clientId, token, function (err, result) {
        if (err) {
            logger.error('Error happened when bindClientId' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Error happened when bindClientId', 1001));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null, 1001));

            toolUtil.putMessageQAMQ({msgType: 'setUserTag', uid: token, vCode: vcode})
        }
    })
};


/**
 * User login, The loginId could be userID, email or phone number;
 */
exports.login = function (req, res) {

    var mobilePhone = req.body.mobilePhone;
    var userPassword = req.body.userPassword;
    var clientId = req.body.clientId;
    var lang = req.cparams.lang;

    var password = md5(userPassword);

    var clientIp = toolUtil.getClientIp(req); // 用户IP地址

    logger.debug('Trying to login with ' + mobilePhone);
    userService.loginService(mobilePhone, password, clientId, clientIp, function (err, results) { // 新
    // userService.loginService(mobilePhone, password, clientId, function (err, results) { // 旧
        if (err) {

            var message = {
                "deviceId": req.params.deviceId,
                "mobilePhone": mobilePhone,
                "password": userPassword,
                "message": err.message
            };
            toolUtil.putMessageLoginOrRegisterLogMQ(message);

            logger.error(loginId + ' Exception happened when login to the system...!-' + err.message);
            res.json(messageUtil.composeFailedMessage(req, mobilePhone + ' Exception happened when login to the system...!-' + err.message, 1002));
        } else {
            //只要结果集中有一个返回值，则表明有记录，说明用户合法
            if (results[0] != null) {
                if (results[0].frozenOrNot) {
                    var errorMsg = 'Account Frozen';
                    if (!lang)
                        errorMsg = '帐号被冻结';

                    res.json(messageUtil.composeFailedMessage(req, errorMsg, 1002));
                } else {
                    var _id = results[0]._id;
                    logger.debug(mobilePhone + ' Logined into the system successfully...!');
                    //获取token并缓冲
                    var token = toolUtil.generateAndCacheToken(_id);
                    var loginUserData = {
                        "_id": _id,
                        "token": token
                    };
                    res.json(messageUtil.composeSucceededMessage(req, 'login into the system successfully...', loginUserData, 1002));
                    toolUtil.setUserByToken(token);
                }
            }
            else {
                var message = {
                    "deviceId": req.params.deviceId,
                    "mobilePhone": mobilePhone,
                    "password": userPassword,
                    "message": "invalid loginID or password"
                };
                toolUtil.putMessageLoginOrRegisterLogMQ(message);
                logger.debug(mobilePhone + ' Failed to login to the system,invalid loginID or password...!');

                var errorMsg = 'Invalid Login or Password.';
                if (!lang)
                /*  宝宝树66小区二次改造    add   guo.xiaomin  20170902   start   */
                    // errorMsg = '用户名或密码错误'; // 旧
                    errorMsg = '请用正确的手机号和宝宝树密码登录'; // 新
                /*  宝宝树66小区二次改造    add   guo.xiaomin  20170902   end   */

                res.json(messageUtil.composeFailedMessage(req, errorMsg, 1002));
            }
        }
    })
};


/*  宝宝树66小区二次改造    add   guo.xiaomin  20170901   start   */
exports.checkServiceAccount = function (mobilePhone, password, callback) {

    var data = {};
    // 是小6客服账号
    if(serviceAccounts.indexOf(mobilePhone) >= 0) {
        var opt = {mobilePhone: mobilePhone, userPassword: md5(password)};
        Users.findOne(opt, '_id userName frozenOrNot encUserId email mobilePhone birthDate userRole nickName communityWay age gender maritalStatus hasChildren images apartmentDetail hobbies community homeTown.country homeTown.province homeTown.city homeTown.county huanxinUserName appSetting userType speciality userPortrait job school authenticationStatus roomUnit roomNumber showUnit invitationCode invitedBy children dateCreated')
            .populate('userPortrait', 'portraitURL value')
            .populate('community', '_id communityName communityName_en_US pinyin communityAddress communityLogo unitSwitch')
            .populate('homeTown.country', '_id name')
            .populate('homeTown.province', '_id name')
            .populate('homeTown.city', '_id name')
            .populate('homeTown.county', '_id name')
            .populate('hobbies', '_id value')
            .exec(function (err, result) {
                if(result != null) {
                    if (!result.authenticationStatus) {
                        result.invitationCode = undefined;
                    }

                    if (result.roomUnit != null && result.roomUnit != '')
                        result._doc.roomUnit = Number(vCode) >= 106000 && !isNaN(result.roomUnit) ? result.roomUnit + '单元' : result.roomUnit;

                    if (result.images.length == 1) {
                        result.images.push(result.images[0])
                    }

                    if (result.communityWay == null) {
                        result._doc.communityWay = 1;
                    }
                }
                data.isServiceAccount = true;
                data.user = result;
                callback(err, data);
            });
    } else {
        // 不是小6客服账号
        data.isServiceAccount = false;
        callback(null, data);
    }

};
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170901   end   */

//新接口
exports.appLogin = function (req, res) {
    var mobilePhone = req.body.mobilePhone;
    var userPassword = req.body.userPassword;
    var vCode = req.cparams.vcode;
    var lang = req.cparams.lang;
    var vName = req.query.vname; // 版本号

    // var password = md5(userPassword);
    var password = userPassword;
    logger.debug('Trying to login with ' + mobilePhone);

    var clientIp = toolUtil.getClientIp(req); // 用户IP地址

    /*  宝宝树66小区二次改造    add   guo.xiaomin  20170901   start   */
    exports.checkServiceAccount(mobilePhone, password, function (err, data) {
        var isServiceAccount = data.isServiceAccount;
        if(isServiceAccount) {
            var user = data.user;
            // 登陆失败
            if(user == null) {
                var message = {
                    "deviceId": req.params.deviceId,
                    "mobilePhone": mobilePhone,
                    "password": userPassword,
                    "message": "invalid loginID or password"
                };

                var errorMsg = 'Invalid Account or Password.';
                if (!lang)
                /*  宝宝树66小区二次改造    add   guo.xiaomin  20170902   start   */
                    // errorMsg = '用户名或密码错误'; // 旧
                    errorMsg = '请用正确的手机号和宝宝树密码登录'; // 新
                /*  宝宝树66小区二次改造    add   guo.xiaomin  20170902   end   */

                logger.debug(mobilePhone + ' Failed to login to the system,invalid loginID or password...!');
                res.json(messageUtil.composeFailedMessage(req, errorMsg, 1002));
                toolUtil.putMessageLoginOrRegisterLogMQ(message);
            } else {
                // 登陆成功
                var resultData = user;
                var token = toolUtil.getUserTokenById(user._id);
                resultData['token'] = token;
                /* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 add wangcan 20170927 start */
                // if (results[7] == null || newProtocolVersion != results[7])
                userService.updateProtocolVersionService(mobilePhone, function (err, results) {
                    if (err) {
                        logger.error("更新最新用户协议版本号出错");
                    } else {
                        logger.info("更新最新用户协议版本号成功");
                    }
                });
                /* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 add wangcan 20170927 end */
                res.json(messageUtil.composeSucceededMessage(req, 'login into the system successfully...', resultData, 1002));
                toolUtil.setUserByToken(token, true);
            }
        } else { // 不是小6客服账号
            /*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170824   start   */
            // userService.appLoginService(deviceId, channelId, mobilePhone, password, null, vCode, function (err, results) {
            userService.appLoginService(req.query.type, req.params.deviceId, req.query.channelId, mobilePhone, password, null, vCode, vName, clientIp, function (err, results) { // 新
            // userService.appLoginService(req.query.type, req.params.deviceId, req.query.channelId, mobilePhone, password, null, vCode, vName, function (err, results) { // 旧
                    /*  宝宝树66小区二期拼团    add  注册极验证 luolh  20170824   end   */
                if (err) {

                    var message = {
                        "deviceId": req.params.deviceId,
                        "mobilePhone": mobilePhone,
                        "password": userPassword,
                        "message": err.message
                    };
                    logger.error(mobilePhone + 'Exception happened when login to the system...!-' + err.message);
                    // res.json(messageUtil.composeFailedMessage(req, mobilePhone + ' Exception happened when login to the system...!-' + err.message, 1002));
                    res.json(messageUtil.composeFailedMessage(req, err.message, 1002));
                    toolUtil.putMessageLoginOrRegisterLogMQ(message);
                } else {
                    /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   start */
                    // 0,1,2,3,4,5->添加[a],0,[b],1,2,3,4,5->[a]0,[0]1,[b]2,[1]3,[2]4,[3]5,[4]6,[5]7
                    //只要结果集中有一个返回值，则表明有记录，说明用户合法
                    //if (results[0] != null) {
                    if (results[1] != null) {
                        //if (results[0].frozenOrNot) {
                        if (results[1].frozenOrNot) {
                            var errorMsg = 'Account Frozen';
                            if (!lang)
                                errorMsg = '帐号被冻结';

                            res.json(messageUtil.composeFailedMessage(req, errorMsg, 1002));
                        } else {
                            var _id = results[1]._id;
                            // var _id = results[0]._id;
                            logger.debug(mobilePhone + ' Logined into the system successfully...!');
                            //获取token并缓冲
                            var token = toolUtil.getUserTokenById(_id);
                            // var data = results[0];
                            var data = results[1];
                            data.frozenOrNot = undefined;
                            /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   start */
                            if (results[0]) {
                                // 宝宝树直接登录
                                data._doc['loginStr'] = results[0].loginStr;
                                data._doc['meitunToken'] = results[0].token;
                            } else {
                                // 老用户注册后登录
                                data._doc['loginStr'] = results[2].loginStr;
                                data._doc['meitunToken'] = results[2].token;
                            }
                            /* 宝宝树66小区二期拼团    add 登录注册接口变更  llh  20170822   end */


                            data._doc['token'] = token;
                            data._doc['auth'] = results[3];
                            data._doc['vStatus'] = results[4];
                            data._doc['isSignIn'] = results[5];
                            data._doc['taskFlag'] = results[7];
                            // data._doc['auth'] = results[1];
                            // data._doc['vStatus'] = results[2];
                            // data._doc['isSignIn'] = results[3];
                            // data._doc['taskFlag'] = results[5];

                            //if (results[4] != null) {
                            if (results[6] != null) {
                                data._doc['communityApply'] = results[6];
                                // data._doc['communityApply'] = results[4];
                            }

                            /* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 add wangcan 20170927 start */
                            // if (results[7] == null || newProtocolVersion != results[7])
                            userService.updateProtocolVersionService(mobilePhone, function (err, results) {
                                if (err) {
                                    logger.error("更新最新用户协议版本号出错");
                                } else {
                                    logger.info("更新最新用户协议版本号成功");
                                }
                            });
                            /* 宝宝树66小区二次改造 新老用户登录勾选新用户协议 add wangcan 20170927 end */

                            res.json(messageUtil.composeSucceededMessage(req, 'login into the system successfully...', data, 1002));
                            toolUtil.setUserByToken(token, true);
                        }
                    } else {
                        var message = {
                            "deviceId": req.params.deviceId,
                            "mobilePhone": mobilePhone,
                            "password": userPassword,
                            "message": "invalid loginID or password"
                        };

                        var errorMsg = 'Invalid Account or Password.';
                        if (!lang)
                        /*  宝宝树66小区二次改造    add   guo.xiaomin  20170902   start   */
                            // errorMsg = '用户名或密码错误'; // 旧
                            errorMsg = '请用正确的手机号和宝宝树密码登录'; // 新
                        /*  宝宝树66小区二次改造    add   guo.xiaomin  20170902   end   */

                        logger.debug(mobilePhone + ' Failed to login to the system,invalid loginID or password...!');
                        res.json(messageUtil.composeFailedMessage(req, errorMsg, 1002));
                        toolUtil.putMessageLoginOrRegisterLogMQ(message);
                    }
                }
            })
        }
    });
    /*  宝宝树66小区二次改造    add   guo.xiaomin  20170901   end   */
};

/* 宝宝树66小区三次改造 mod guo.xiaomin 20170928 start */
// 美囤第三方登陆(前端传递logstr)
exports.appMtLogin = function (req, res) {
    // 美囤登陆
    // var token = req.params.token;
    // var vCode = req.cparams.vcode;
    // var lang = req.cparams.lang;
    // var vName = req.query.vname; // 版本号

    var ipAddr = toolUtil.getClientIp(req); // 客户端IP地址
    var deviceId = req.params.deviceId;   // deviceId(设备唯一标示符)

    // 前台传递loginStr
    // u35702925591_e49d517b976c49adaf275bc9763b6a7d_1506429506
    // encUserId_?_手机号码
    var loginStr = req.body.loginStr;
    var loginStrArray = [];
    var encUserId = null;
    var loginId = null;
    logger.info('loginStr...' + loginStr);
    if(loginStr) {
        loginStrArray = loginStr.split('_');
        if (loginStrArray.length == 3) {
            encUserId = loginStrArray[0];
            loginId = loginStrArray[2];
            userService.appMtLoginService(loginStr, loginId, encUserId, req.query.type, deviceId, req.query.channelId, ipAddr, function (err, results) {
                if (err) {

                    var message = {
                        "deviceId": deviceId,
                        "mobilePhone": loginStr,
                        "password": '',
                        "message": err.message
                    };
                    logger.error(loginStr + 'Exception happened when appMtLogin to the system...!-' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, err.message, 1002));
                    toolUtil.putMessageLoginOrRegisterLogMQ(message);
                } else {
                    logger.info('userService.appMtLoginService success....');
                    if (results[1] != null) {
                        if (results[1].frozenOrNot) {
                            var errorMsg = 'Account Frozen';
                            if (!lang)
                                errorMsg = '帐号被冻结';

                            res.json(messageUtil.composeFailedMessage(req, errorMsg, 1002));
                        } else {
                            var _id = results[1]._id;
                            logger.debug(loginStr + ' Logined into the system successfully...!');
                            //获取token并缓冲
                            var token = toolUtil.getUserTokenById(_id);
                            var data = results[1];
                            data.frozenOrNot = undefined;
                            // 宝宝树直接登录
                            data._doc['loginStr'] = results[0].loginStr;
                            data._doc['meitunToken'] = results[0].token;
                            data._doc['token'] = token;
                            data._doc['auth'] = results[2];
                            data._doc['vStatus'] = results[3];
                            data._doc['isSignIn'] = results[4];
                            data._doc['taskFlag'] = results[6];
                            if (results[6] != null) {
                                data._doc['communityApply'] = results[5];
                            }
                            res.json(messageUtil.composeSucceededMessage(req, 'login into the system successfully...', data, 1002));
                            toolUtil.setUserByToken(token, true);
                        }
                    } else {
                        var message = {
                            "deviceId": deviceId,
                            "mobilePhone": loginStr,
                            "password": '',
                            "message": err.message
                        };
                        logger.error(loginStr + 'Exception happened when appMtLogin to the system...!-' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 1002));
                        toolUtil.putMessageLoginOrRegisterLogMQ(message);
                    }
                }
            });
        } else {
            var message = {
                "deviceId": deviceId,
                "mobilePhone": loginStr,
                "password": '',
                "message": 'loginStr 不合法,分割'
            };
            logger.error('loginStr 不合法,分割');
            res.json(messageUtil.composeFailedMessage(req, 'loginStr不合法', 1002));
            toolUtil.putMessageLoginOrRegisterLogMQ(message);
        }
    } else {
        logger.error('loginStr 不合法,空');
        var message = {
            "deviceId": deviceId,
            "mobilePhone": loginStr,
            "password": '',
            "message": 'loginStr不合法'
        };
        res.json(messageUtil.composeFailedMessage(req, 'loginStr不合法', 1002));
        toolUtil.putMessageLoginOrRegisterLogMQ(message);
    }
};
/* 宝宝树66小区三次改造 mod guo.xiaomin 20170928 end */

/**
 * 获取用户权限列表
 */
exports.getUserAuthList = function (req, res) {
    var token = req.params.token;

    userService.getUserAuthListService(token, function (err, result) {
        if (err) {
            logger.error('Error happened when getUserAuthList' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1003));
        } else {
            var data = {
                auth: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 1003));
        }
    })
};


/*  宝宝树66小区二次改造    add   guo.xiaomin  20170802   start   */
// 取得用户是否被禁言
exports.getUserGagOrNot = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to getUserGagOrNot - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to getUserGagOrNot - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to getUserGagOrNot - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to getUserGagOrNot! - " + gagOrNot);
                res.json(messageUtil.composeSucceededMessage(req, null, gagOrNot, 1003));
            }
        }
    });
};
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    add   guo.xiaomin  20170919   start   */
// 根据手机号查询当前用户是否是66小区用户 1:是;0:不是
exports.isBabyTreeUser = function (req, res) {
    // 手机号
    var mobilePhone = req.body.mobilePhone;

    userService.isBabyTreeUser(mobilePhone, function (err, tempCount) {
        if (err) {
            logger.error("Failed to isBabyTreeUser - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to isBabyTreeUser - " + err.message));
        } else {
            logger.debug("Succeeded to isBabyTreeUser! - " + tempCount);
            res.json(messageUtil.composeSucceededMessage(req, null, tempCount, 1003));
        }
    });
};
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170919   end   */

/**
 * 第三方登录   1.1.2开始
 */
exports.appThirdPartyLogin = function (req, res) {
    var thirdId = req.params.thirdId;
    var input = req.body;
    var deviceId = req.params.deviceId;
    var vCode = req.cparams.vcode;
    var type = req.cparams.type;

    thirdId = thirdId.toLowerCase();

    var clientIp = toolUtil.getClientIp(req); // 用户IP地址

    userService.appThirdPartyLoginService(thirdId, input, deviceId, vCode, type, clientIp, function (err, result) { // 新
    // userService.appThirdPartyLoginService(thirdId, input, deviceId, vCode, type, function (err, result) { // 旧
        if (err) {
            logger.error('Exception happened when login by appThirdPartyLogin...!-' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1004));
        } else {
            var data = result[2];
            data._doc['firstLogin'] = result[1];
            res.json(messageUtil.composeSucceededMessage(req, 'login into the system successfully...', data, 1004));

            if (result[1] && input.image != null && input.image != '') {
                toolUtil.putMessageThirdPartyImageMQ({user: data._id, image: input.image})
            }
        }
    })
};

/**
 * user-controller.js
 *微信登录
 *author：chenjinzhuan
 * */
exports.loginViaWeChat = function (req, res) {

    var wechatId = req.params.wechatId;
    var input = req.body;
    var clientId = input.clientId;
    logger.debug('login by wechat...');

    userService.loginViaWeChatService(wechatId, input.nickName, input.image, clientId, function (err, user) {
        if (err) {
            logger.error(wechatId + ' Exception happened when login by wechat...!-' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1004));
        } else {

            //获取token并缓冲
            var token = toolUtil.generateAndCacheToken(user._id);
            var loginUserData;
            if (user._doc.firstLogin) {
                loginUserData = {
                    "_id": user._id,
                    "token": token,
                    "firstLogin": user._doc.firstLogin,
                    "nickName": user.nickName,
                    "huanxinUserName": user.huanxinUserName,
                    "appSetting": user.appSetting,
                    "userType": user.userType,
                    "images": user.images,
                    "authenticationStatus": user.authenticationStatus
                };
                redisClient.sadd('u:all', user._id);
            } else {
                loginUserData = user;
                user._doc['token'] = token;
                if (user._doc.community != null) {
                    user._doc['communityId'] = user._doc.community._id;
                    user._doc['communityName'] = user._doc.community.communityName;
                }
                user._doc.community = undefined;
                user.frozenOrNot = undefined;
            }
            toolUtil.setUserByToken(token);
            res.json(messageUtil.composeSucceededMessage(req, 'login into the system successfully...', loginUserData, 1004));
        }
    })
};


exports.logout = function (req, res) {
    var token = req.params.token;

    userService.logoutService(token, function (err, result) {
        if (err) {
            logger.error('Error happened when logout from the application...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Error happened when logout from the application...!', 1005));
        } else {
            logger.debug('logout from the application...!');
            res.json(messageUtil.composeSucceededMessage(req, 'logged out from the application...', null, 1005));
        }
    });
};

/**
 * Find user by User userId
 * userId is the MongoDB id created by the database;
 */
exports.findById = function (req, res) {
    var id = req.params.userId;
    var vCode = req.cparams.vcode;

    logger.debug('Retrieving a User: ' + id);
    userService.findByIdService(id, vCode, function (err, user) {
        if (err) {
            logger.error('Exception happened when trying to find user based on user userId...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to find user based on user userId...!', 1006));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, user, 1006));
        }
    });
};

/**
 * User profile update based on the user's userId
 */
exports.updateUser = function (req, res) {

    var token = req.params.token;
    var input = req.body;
    var vcode = Number(req.query.vcode);

    userService.updateService(token, input, vcode, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to update the user data...!' + err.message);
            logger.info(input);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1007));
        } else {
            logger.debug("Update user profile successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, null, 1007));
            toolUtil.setUserByToken(token);
        }
    })
};


/**
 * 生成验证码
 */
exports.generateVerificationCode = function (req, res) {

    logger.debug("To generate a verificationCode for mobile client...!");
    var deviceId = req.params.deviceId;
    var mobilePhone = req.params.mobilePhone;
    var flag = req.params.flag;

    var lang = req.cparams.lang;

    if (mobilePhone == null) {
        logger.error('Please provide the mobilePhone No....');
        res.json(messageUtil.composeFailedMessage(req, 'Please provide the mobilePhone No....'));
    } else {
        userService.findUserService(mobilePhone, function (err, result) {
            if (err) {
                logger.error('Exception happened when apply to be expert ...!' + err.message);
                res.json(messageUtil.composeFailedMessage(req, ''));
            } else {
                if (mobilePhone.length != 11) {
                    var errorMsg = 'Incorrect Phone number';
                    if (!lang)
                        errorMsg = '请输入正确的手机号';

                    res.json(messageUtil.composeFailedMessage(req, errorMsg));
                } else {
                    if (flag == 'register') {
                        if (result != null) {
                            var errorMsg = 'Account has been registered, please sign in';
                            if (!lang)
                                errorMsg = '账号已注册请登录';

                            res.json(messageUtil.composeFailedMessage(req, errorMsg));
                        } else {
                            var message = {
                                "deviceId": deviceId,
                                "mobilePhone": mobilePhone,
                                "verificationCode": toolUtil.generateVerificationCode(mobilePhone, mobilePhone)
                            };
                            var tempData = {
                                "verificationCode": message.verificationCode
                            };
                            res.json(messageUtil.composeSucceededMessage(req, null, tempData));

                            toolUtil.putMessageVerificationCodeMQ(message);
                        }
                    } else if (flag == 'forget') {
                        if (result == null) {
                            var errorMsg = 'This number has NOT been registered, please sign up';
                            if (!lang)
                                errorMsg = '您的号码未注册';

                            res.json(messageUtil.composeFailedMessage(req, errorMsg));
                        } else {
                            var message = {
                                "deviceId": deviceId,
                                "mobilePhone": mobilePhone,
                                "verificationCode": toolUtil.generateVerificationCode(mobilePhone, mobilePhone)
                            };
                            toolUtil.putMessageVerificationCodeMQ(message);
                            var tempData = {
                                "verificationCode": message.verificationCode
                            };
                            res.json(messageUtil.composeSucceededMessage(req, null, tempData));
                        }
                    }
                }
            }
        })
    }
};


/**
 * check验证码
 */
exports.checkVerificationCode = function (req, res) {
    logger.debug("To check a verificationCode for mobile client...!");
    var mobilePhone = req.params.mobilePhone;
    var verificationCode = req.params.verificationCode;

    if (mobilePhone != null && verificationCode != null) {
        cacheUtil.cacheGet(mobilePhone, function (err, result) {
            if (result != null && result == verificationCode) {
                logger.debug("Succeeded to check a verificationCode - " + mobilePhone);
                res.json(messageUtil.composeSucceededMessage(req, null, null));
            } else {
                logger.error("Failed to check code ! - invalid verification code!");
                var lang = req.cparams.lang;

                var errorMsg = 'Invalid verification code';
                if (!lang)
                    errorMsg = '验证码错误';

                res.json(messageUtil.composeFailedMessage(req, errorMsg));
            }
        });
    } else {
        logger.error("Failed to Check verificationCode ! - You have to provide at least mobilePhone +  verificationCode for check...!");
        res.json(messageUtil.composeFailedMessage(req, 'Failed to Check verificationCode ! - You have to provide at least mobilePhone +  verificationCode for check...!'));
    }
};

//验证token
exports.checkToken = function (req, res) {
    var token = req.params.token;
    var vCode = req.cparams.vcode;

    userService.checkTokenService(token, vCode, function (err, results) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, err.message, 1008));
        } else {
            toolUtil.setUserByToken(token);
            var data = results[0];
            data['token'] = encodeURIComponent(token);
            data['auth'] = results[1];
            data['vStatus'] = results[2];
            data['isSignIn'] = results[3];
            data['taskFlag'] = results[5];

            delete data.mobilePhone;

            if (results[4] != null) {
                data['communityApply'] = results[4];
            }
            res.json(messageUtil.composeSucceededMessage(req, null, data, 1008));

            //marketService.initSmartGoodsListService(token);
        }
    });
};

/**
 * user-controller.js
 *重置密码
 *author：chenjinzhuan
 * */
exports.resetPassword = function (req, res) {
    logger.debug("To reset password....");
    var mobilePhone = req.params.mobilePhone;
    var newPassword = req.params.newPassword;

    var clientIp = toolUtil.getClientIp(req); // 用户IP地址

    userService.resetPasswordService(mobilePhone, newPassword, clientIp, function (err, results) { // 新
    // userService.resetPasswordService(mobilePhone, newPassword, clientIp, function (err, results) { // 旧
        if (err) {
            logger.error('Exception happened when trying to rest the user password...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to rest the user password...!'));
        } else {
            logger.debug("Reset user password successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
};


/**
 * user-controller.js
 *修改密码
 *author：chenjinzhuan
 * */
exports.changePassword = function (req, res) {
    var id = toolUtil.getUserObjIdByToken(req.params.token);
    var userName = req.params.userName;
    var input = req.body;
    logger.debug('Change password.... - ' + id);

    var clientIp = toolUtil.getClientIp(req); // 用户IP地址

    userService.changePaswordService(id, userName, input, clientIp, function (err) { // 新
    // userService.changePaswordService(id, userName, input, function (err) { // 旧
        if (err) {
            logger.error('Exception happened when changing password...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1009));
        } else {
            logger.debug("Change password successfully...!");
            var lang = req.cparams.lang;

            var errorMsg = 'Password changed successfully';
            if (!lang)
                errorMsg = '修改密码成功';

            res.json(messageUtil.composeSucceededMessage(req, errorMsg, null, 1009));
        }
    });
};

/*  宝宝树66小区五期安全漏洞    add  登陆极验证 guo.xiaomin  20171116   start   */
// 1120-commit-master
// 修改密码极验证1次
exports.captchChangePassword = function (req, res) {
    var userId = toolUtil.getUserObjIdByToken(req.params.token); // 用户ID
    var deviceId = req.params.deviceId; // 设备ID
    logger.debug("captchChangePassword:userId + deviceId..." + userId + " + " + deviceId);
    var data = {
        client_type : 'h5',
        native :'unknown',
        ip_address:'unknnow'
    };
    var captcha = new Geetest({
        geetest_id: geetest_id,
        geetest_key: geetest_key
    });
    captcha.register(data, function (err, data) {
        if (err) {
            console.error(err);
            return;
        }
        if (!data.success) {
            // 进入 fallback，如果一直进入此模式，请检查服务器到极验服务器是否可访问
            // 可以通过修改 hosts 把极验服务器 api.geetest.com 指到不可访问的地址
            // 为以防万一，你可以选择以下两种方式之一：
            // 1. 继续使用极验提供的failback备用方案
            req.session.fallback = true;
            logger.debug("fallback:true" + deviceId);
            redisClient.setex('captchChangePassword:fallback:' + userId + ":" + deviceId, 86400, true);
            res.send(data);
            // 2. 使用自己提供的备用方案
            // todo
        } else {
            // 正常模式
            logger.debug("fallback:false"+req.session.id);
            redisClient.setex('captchChangePassword:fallback:' + userId + ":" + deviceId, 86400, false);
            req.session.fallback = false;
            res.send(data);
        }
    });
};

// 修改密码极验证2次
exports.captchValidateChangePassword = function (req, res) {
    userService.captchValidateChangePassword(req, function(err, result){
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, "Invalid validate"));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, {success: result}, 2005))
        }
    });
};

// 修改密码获取验证码
exports.getSmsCodeChangePwd = function (req, res) {

    var mobilePhone = req.body.mobilePhone; // 手机号
    var token = req.params.token;

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var tempMobilePhone = user.mobilePhone;
            if (mobilePhone != tempMobilePhone) {
                logger.debug("token取得手机号和参数手机号不一致..." + token + "@" + mobilePhone);
                res.json(messageUtil.composeErrorMessage(req, {status: 0, message: "非法操作"}, 2002))
            } else {
                var userId = toolUtil.getUserObjIdByToken(token); // 用户ID
                var deviceId = req.params.deviceId; // 设备ID
                logger.debug("changePasswordNew:userId + deviceId..." + userId + " + " + deviceId);

                logger.debug("getSmsCodeChangePwd:mobilePhone + userId +  deviceId..." + mobilePhone + " + " + userId + " + " + deviceId);
                redisClient.get('captchChangePassword:fallback:' + userId + ":" + deviceId, function (err, value) {
                    if (err || value == null || value == "false") {
                        logger.debug("captchChangePassword:fallback error...");
                        res.json(messageUtil.composeErrorMessage(req, {status: 0, message: "非法操作"}, 2002))
                    } else {
                        var type = req.body.type;
                        // 修改密码只能是4
                        if (type == '4') {
                            var keyA = 'day:' + moment().format('YYYYMMDD') + ':mobile:' + mobilePhone + ':' + type + ':sms:count';

                            redisClient.get(keyA, function (err, value) {
                                if (Number(value) < 5) {
                                    appService.getSmsVerificationCodeService(mobilePhone, type, function (err, result) {
                                        if (err) {
                                            logger.error('Failed to getSmsVerificationCode---' + err.message);
                                            res.json(messageUtil.composeErrorMessage(req, err, 2002))
                                        } else {

                                            res.json(messageUtil.composeSucceededMessage(req, null, null, 2002));

                                            //push到短信发送队列
                                            var message = {
                                                "deviceId": deviceId,
                                                "mobilePhone": mobilePhone,
                                                "verificationCode": result,
                                                "type": type
                                            };
                                            toolUtil.putMessageVerificationCodeMQ(message);

                                            // 追加频率限制-start
                                            redisClient.incr(keyA, function (err, reply) {
                                                redisClient.expire(keyA, 86400); // 1天
                                            });
                                            // 追加频率限制-end

                                            if (type == '1' || type == '2' || type == '4') {

                                                var typeDesc = "";
                                                if (type == '1') {
                                                    typeDesc = '短信验证码（注册）';
                                                } else if (type == '2') {
                                                    typeDesc = '短信验证码（忘记密码）';
                                                } else if (type == '4') {
                                                    typeDesc = '短信验证码（修改密码）';
                                                }
                                                var clickMessage = {
                                                    type: type == '1' ? 45 : 48,
                                                    typeDesc: typeDesc,
                                                    deviceId: deviceId,
                                                    ext: mobilePhone,
                                                    vname: req.query.vname,
                                                    vcode: req.query.vcode,
                                                    os: req.query.type,
                                                    createTime: new Date().getTime()
                                                };

                                                toolUtil.putMessageLogMQ(clickMessage);
                                            }
                                            // 重新发送可行
                                            // redisClient.setex('captchChangePassword:fallback:'+ userId + ":" + deviceId, 86400, false);
                                            redisClient.setex('captchChangePassword:nextFlag:' + userId + ":" + deviceId, 86400, true);
                                        }
                                    });
                                } else {
                                    res.json(messageUtil.composeErrorMessage(req, {
                                        status: 0,
                                        message: '发送失败，当天短信数量超出限制'
                                    }, 2002));
                                }
                            });
                        } else {
                            logger.debug("修改密码使用type错误...");
                            res.json(messageUtil.composeErrorMessage(req, {status: 0, message: '非法操作'}, 2002))
                        }
                    }
                });
            }
        }
    });
};

// 真正修改密码
exports.changePasswordNew = function (req, res) {

    var userId = toolUtil.getUserObjIdByToken(req.params.token); // 用户ID
    var deviceId = req.params.deviceId; // 设备ID
    var mobilePhone = req.body.mobilePhone; // 手机号
    logger.debug("changePasswordNew:userId + deviceId..." + userId + " + " + deviceId);
    redisClient.get('captchChangePassword:nextFlag:' + userId + ":" + deviceId, function (err, value) {
        if (err || value == null || value == "false") {
            logger.error("captchChangePassword:nextFlag:" + value);
            res.json(messageUtil.composeErrorMessage(req, {status:0,message:"非法操作"}, 2002))
        } else {
            logger.debug("captchChangePassword:nextFlag:" + value);
            var code = req.body.code;
            var verKey = 'ver:code:' + mobilePhone + ':4'; // 修改密码
            var errorKey = verKey + ":errorCount";

            redisClient.get(errorKey, function(err, getReply) {
                if (getReply != null && getReply >= 3) {
                    logger.debug("验证码错误次数太多，锁定1小时!..." + errorKey);
                    res.json(messageUtil.composeErrorMessage(req, {status:0, message:"验证码错误次数太多，锁定1小时!"}, 2002))
                } else {
                    redisClient.get(verKey, function (err, value2) {
                        logger.debug('ver:code:' + mobilePhone + ':4...' + value2 + "@" + code);
                        if (value2 != null && value2 == code) {
                            // 正常修改密码
                            var userName = req.params.userName;
                            var input = req.body;
                            logger.debug('Change password.... - ' + userId);

                            var clientIp = toolUtil.getClientIp(req); // 用户IP地址

                            userService.changePaswordService(userId, userName, input, clientIp, function (err) {
                                if (err) {
                                    logger.error('Exception happened when changing password...!' + err.message);
                                    res.json(messageUtil.composeFailedMessage(req, err.message, 1009));
                                } else {
                                    logger.debug("Change password successfully...!");
                                    var lang = req.cparams.lang;

                                    var errorMsg = 'Password changed successfully';
                                    if (!lang)
                                        errorMsg = '修改密码成功';

                                    res.json(messageUtil.composeSucceededMessage(req, errorMsg, null, 1009));
                                }
                            });
                        } else {
                            redisClient.incr(errorKey, function(err, reply) {
                                redisClient.expire(errorKey, 3600); // 1小时
                                logger.error('验证码错误:ver:code:' + mobilePhone + ':4...' + value2 + "@" + code);

                                var lang = req.cparams.lang;
                                // 异常注册
                                var errorMsg = 'invalid signUp.';
                                if (!lang)
                                    errorMsg = '修改密码异常.';
                                res.json(messageUtil.composeFailedMessage(req, errorMsg, 2006))
                            });
                        }
                    });
                }
            });
        }
    });
};
/*  宝宝树66小区五期安全漏洞    add  登陆极验证 guo.xiaomin  20171116   end   */

//========================================================================

/**
 * 设置(上传和修改)个人图像
 * multiPart Body, with a name as "image"
 */

exports.uploadUserProfileImage = function (req, res) {

    var objectName = 'user';
    var token = req.params.token;
    var id = toolUtil.getUserObjIdByToken(token);


    toolUtil.uploadImageService(objectName, id, req, function (err, images) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, 'Failed to upload user profile Images... - ' + err.message));
        } else {
            var tempImages = [];
            var k = 0;
            for (i = 0; i < images.length; i++) {
                if (images[i] != null)
                    tempImages[k++] = {
                        "imageURL": images[i]
                    }
            }
            userService.setImagesToUser(id, tempImages, function (err, result) {
                if (err || tempImages == null) {
                    res.json(messageUtil.composeFailedMessage(req, 'Failed to upload user profile Images... - ' + err.message));
                } else {
                    var data = {
                        images: tempImages
                    };
                    res.json(messageUtil.composeSucceededMessage(req, null, data));
                }
            });
        }
    })
};

/**
 * 设置用户小区信息
 * @param req
 * @param res
 */
exports.setUserCommunity = function (req, res) {
    var token = req.params.token;
    var input = req.body;
    var id = toolUtil.getUserObjIdByToken(token);
    userService.setUserCommunityService(token, input, function (err, results) {
        logger.info(results);

        if (err) {
            logger.error('Exception happened when trying to update the user data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to update the user data...!'));
        } else {
            logger.debug("Update user profile successfully...!");
            var id = {
                "_id": results
            };
            logger.info(id);
            toolUtil.setUserByToken(token);
            res.json(messageUtil.composeSucceededMessage(req, null, id));
        }
    })
};

/**
 * 设置小区新接口  1.1.2
 */
exports.setUserCommunityNew = function (req, res) {
    var token = req.params.token;
    var communityId = req.params.communityId;
    var invite = req.query.invite;

    userService.setUserCommunityNewService(token, communityId, 1, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to setUserCommunityNew...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1010));
        } else {

            toolUtil.setUserByToken(token);
            res.json(messageUtil.composeSucceededMessage(req, null, result[0], 1010));

            redisClient.SCARD('u:c:' + communityId, function (err, value) {
                if (Number(value) == 1 && !result[0].isInit) {
                    userService.initCommunityQuestionService(communityId);
                }
            });

            if (result.length > 1 && result[5] == null) {

                /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170815   start   */
                // 用户注册，自动发帖的createBy有误
                // appService.sendInviteRewardService(token, invite); // 旧
                toolUtil.getUserByToken(token, function (err, user) {
                    if (user == null) {
                        logger.error('Exception happened when getUserByToken...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 1010));
                    } else {
                        appService.sendInviteRewardService(user._id, invite);
                    }
                });
                /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170815   end   */

                // toolUtil.putMessageBusinessMQ({
                //     msgType: 'new_people_push',
                //     userId: token
                // });
            }
        }
    })
};

exports.addCommunity = function (req, res) {
    var token = req.params.token;
    var communityId = req.params.communityId;

    userService.addCommunityService(token, communityId, function (err, result) {

        if (err) {
            logger.error('Failed to addCommunity ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1041))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 1041));

            if (!result.isInit) {
                userService.initCommunityQuestionService(communityId);
            }
        }
    });
};

exports.getUserCommunityList = function (req, res) {
    var token = req.params.token;
    userService.getUserCommunityListService(token, function (err, result) {
        if (err) {
            logger.error('Failed to getUserCommunityList ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1042))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 1042));
        }
    })
};

/*  宝宝树66小区二次改造    add  小区切换 luolh  20170803   start   */
exports.getAmbassadorCommunityList = function (req, res) {
    var token = req.params.token;
    userService.getAmbassadorCommunityListService(token, function (err, result) {
        if (err) {
            logger.error('Failed to getAmbassadorCommunityList ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1042))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 1042));
        }
    })
};
/*  宝宝树66小区二次改造    add  小区切换 luolh  20170803   end   */

exports.backSetUserCommunity = function (req, res) {
    var userId = req.params.userId;
    var communityId = req.params.communityId;

    userService.backSetUserCommunityService(communityId, userId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to backSetUserCommunity...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 111));
        } else {
            toolUtil.setUserByToken(userId);
            res.json(messageUtil.composeSucceededMessage(req, null, null, 111));

            if (!result[0].isInit) {
                userService.initCommunityQuestionService(communityId);
            }

            if (result[1] == null) {
                appService.sendInviteRewardService(userId);

                // toolUtil.putMessageBusinessMQ({
                //     msgType: 'new_people_push',
                //     userId: userId
                // });
            }
        }
    })
};

exports.initCommunity = function (req, res) {
    var communityId = req.params.communityId;

    userService.backInitCommunityService(communityId, function (err, result) {
        if (err) {
            logger.error('Failed to initCommunity ---' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1042))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 1042));
        }
    })
};

/**
 * user-controller.js
 *获取通讯录
 *author：chenjinzhuan
 * */
exports.getContactList = function (req, res) {
    var id = toolUtil.getUserObjIdByToken(req.params.token);
    logger.debug('Get contactlist.... - ' + id);

    userService.getContactListService(id, function (err, contacts) {
        if (err) {
            logger.error('Exception happened when get contactlist...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get contactlist...!'));
        } else {
            //将指定id所有的通讯录返回给客户端
            logger.debug("Get contactlist successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, contacts));
        }
    });
};

/**
 * user-controller.js
 *添加到通讯录
 *author：chenjinzhuan
 * */
exports.addToContactList = function (req, res) {
    var id = toolUtil.getUserObjIdByToken(req.params.token);
    var userName = req.params.userName;
    var userNameToAdd = req.params.userNameToAdd;
    logger.debug('addToContactList.... - ' + id);

    userService.addToContactListService(id, userName, userNameToAdd, function (err) {
        if (err) {
            logger.error('Exception happened when add to contactList...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when add to contactList...!'));
        } else {
            logger.debug('Add to contactlist successfully...!');
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });

    //async.waterfall([
    //    //通过用户名获取用户Id
    //    function (callbackInner) {
    //        userService.getUserIdService(userNameToAdd, callbackInner);
    //    },
    //    //将用户添加到通讯录
    //    function (results) {
    //        logger.debug('userId hello:' + results);
    //        userService.addToContactListService(id, results.userId, function (err, results) {
    //            if (err) {
    //                logger.error('Exception happened when add to contactList...!');
    //                res.json(messageUtil.composeFailedMessage(req,'Exception happened when add to contactList...!'));
    //            } else {
    //                logger.debug('Add to contactlist successfully...!');
    //                res.json(messageUtil.composeSucceededMessage(req,null, null));
    //            }
    //        });
    //    }
    //]);


};

/**
 * user-controller.js
 *从通讯录删除
 *author：chenjinzhuan
 * */
exports.RemoveFromContactList = function (req, res) {
    var id = toolUtil.getUserObjIdByToken(req.params.token);
    var userName = req.params.userName;
    var userNameToRemove = req.params.userNameToRemove;
    logger.debug('RemoveFromContactList.... - ' + id);

    userService.RemoveFromContactListService(id, userName, userNameToRemove, function (err) {
        if (err) {
            logger.debug(err.message);
            logger.error('Exception happened when Remove to contactList...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when Remove to contactList...!'));
        } else {
            logger.debug('Remove to contactlist successfully...!');
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });


    //async.waterfall([
    //    //通过用户名获取用户Id
    //    function (callbackInner) {
    //        userService.getUserIdService(userNameToRemove, callbackInner);
    //    },
    //    //将用户添加到通讯录
    //    function (results) {
    //        //logger.debug('userId hello:' + results);
    //        userService.RemoveFromContactListService(id, results.userId, function (err, results) {
    //            if (err) {
    //                logger.debug(err.message);
    //                logger.error('Exception happened when Remove to contactList...!');
    //                res.json(messageUtil.composeFailedMessage(req,'Exception happened when Remove to contactList...!'));
    //            } else {
    //
    //                //环信删除好友开始
    //                var http = require('http');
    //
    //                //获取环信token
    //                userService.getHuanxinTokenService(function (err, results) {
    //                    if (err) {
    //                        logger.error('Exception happened when remove contactList 1...!');
    //                        res.json(messageUtil.composeFailedMessage(req,'Exception happened when remove contactList 2...!'));
    //                    } else {
    //                        logger.debug('Set Token...!');
    //                        //var resultsParse = JSON.parse(results);
    //                        var resultsParse = results;
    //                        logger.debug('results1: ' + resultsParse);
    //                        logger.debug('results.access_token: ' + resultsParse.access_token);
    //
    //                        //构造链接选项
    //                        var urlOpts = {
    //                            host: 'a1.easemob.com',
    //                            //path: '/easemob-demo/chatdemoui/users/'+userName+'/contacts/users/'+userNameToAdd,
    //                            path: '/66xiaoqu/"+huanxinEnv+"/users/' + userNameToRemove + '/contacts/users/' + userName,
    //                            port: '80',
    //                            method: 'DELETE',
    //                            headers: {
    //                                "Authorization": 'Bearer ' + resultsParse.access_token
    //                            }
    //                        };
    //
    //                        //向环信提交请求
    //                        var request = http.request(urlOpts, function (response) {
    //                            response.on('data', function (chunk) {//请求成功的情况
    //                                logger.debug(chunk.toString());
    //                            });
    //                        }).on('error', function (e) {//请求失败的情况
    //                            logger.debug('error:' + e.stack);
    //                            //添加已经删除的数据库中的好友
    //                            userService.addToContactListService(id, idToRemove, function (err) {
    //                                if (err) {
    //                                    logger.debug(err.message);
    //                                    logger.error('Exception happened when add to contactList in RemoveFromContactList...!');
    //                                    res.json(messageUtil.composeFailedMessage(req,'Exception happened when add to contactList in RemoveFromContactList...!'));
    //                                } else {
    //                                    logger.debug('Add to contactlist successfully in RemoveFromContactList...!');
    //                                }
    //                            });
    //                        });
    //                        // write data to request body
    //                        //request.write(post_data + "\n");
    //                        request.end();
    //                    }
    //                });
    //
    //                //环信删除好友结束
    //
    //                logger.debug('Remove to contactlist successfully...!');
    //                res.json(messageUtil.composeSucceededMessage(req,null, null));
    //            }
    //        });
    //    }
    //]);


};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 关注
 */
exports.followup = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to followup - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to followup - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to followup - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to followup! - " + gagOrNot);

                var category = req.params.category;
                var id = req.params.id;
                userService.followupService(category, token, id, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when followup a question or activity ...!' + err.message + id);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 1011));
                    } else {
                        var followId = {
                            "_id": result._id
                        };
                        res.json(messageUtil.composeSucceededMessage(req, null, followId, 1011));

                        if (category == 'user') {

                            var message = {
                                msgType: 'concern',
                                userId: token,
                                concernUserId: id
                            };
                            toolUtil.putMessageBusinessMQ(message);
                        }
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 取消关注
 */
exports.cancelFollowup = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to cancelFollowup - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to cancelFollowup - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to cancelFollowup - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to cancelFollowup! - " + gagOrNot);

                var category = req.params.category;
                var id = req.params.id;
                userService.cancelFollowupService(category, token, id, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when cancel followup a question or activity ...!' + err.message + id);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 1012));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null, 1012));
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/**
 * 获取某类关注清单
 */
exports.getFollowupList = function (req, res) {
    var category = req.params.category;
    var token = req.params.token;
    var page = req.params.pageNo;

    userService.getFollowupListService(page, category, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get followupList ...!' + token);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get followupList...!', 1013));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results, 1013));
        }
    });
};

exports.getNeighbourList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;
    userService.getNeighbourListService(page, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get neighbour list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get neighbour list...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.applyToBeExpert = function (req, res) {
    var token = req.params.token;
    var input = req.body;

    userService.applyToBeExpertService(token, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when apply to be expert ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when apply to be expert...!' + err.message));
        } else {
            var msg = '已提交申请，请等候审核结果';

            res.json(messageUtil.composeSucceededMessage(req, msg, null));
        }
    })
};

exports.findUser = function (req, res) {
    var id = req.params.id;

    userService.findUserService(id, function (err, result) {
        if (err) {
            logger.error('Exception happened when apply to be expert ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, ''));
        } else {
            if (result == null) {
                res.json(messageUtil.composeFailedMessage(req, '用户不存在'));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, null));
            }
        }
    })
};

exports.getUserProfile = function (req, res) {
    var userId = req.params.userId;
    var token = req.params.token;
    userService.getUserProfileService(userId, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get user profile by userId ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                "isFollowup": results[3],
                "profile": results[1],
                "question": results[2]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

/**
 * 获取用户问题列表
 */
exports.getUserQuestionList = function (req, res) {
    var userId = req.params.userId;
    var pageNo = req.params.pageNo;
    var token = req.params.token;
    userService.getUserQuestionListService(pageNo, userId, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get user question list by userId ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get user question list by userId ...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.getUserQuestionListNew = function (req, res) {
    var userId = req.params.userId;
    var pageNo = req.params.pageNo;
    var token = req.params.token;

    var key = 'catch:user:ugc:' + userId;

    redisClient.HGET(key, pageNo, function (err, value) {
        if (value != null) {
            logger.info('get user ugc from catch');
            res.json(messageUtil.composeSucceededMessage(req, null, JSON.parse(value)))
        } else {
            userService.getUserQuestionListNewService(pageNo, userId, token, function (err, results) {
                if (err) {
                    logger.error('Exception happened when getUserQuestionListNew ...!' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, err.message));
                } else {
                    res.json(messageUtil.composeSucceededMessage(req, null, results));
                    redisClient.HSET(key, pageNo, JSON.stringify(results));
                    redisClient.EXPIRE(key, 300);
                }
            })
        }
    });
};

exports.getHomePage = function (req, res) {
    var token = req.params.token;

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var key = 'homepage:' + user.community._id;

            redisClient.get(key, function (err, value) {
                if (value != null) {
                    logger.info('get homePage from catch');
                    res.json(messageUtil.composeSucceededMessage(req, null, JSON.parse(value)))
                } else {
                    logger.info('get homePage from mongo');
                    userService.getHomePageService(token, function (err, results) {
                        if (err) {
                            logger.error('Exception happened when get home page ...!' + err.message);
                            res.json(messageUtil.composeFailedMessage(req, err.message));
                        } else {

                            var data = {
                                "modules": results[0],
                                "news": results[1],
                                "question": results[2],
                                "special": results[3],
                                "talent": results[4]
                            };
                            res.json(messageUtil.composeSucceededMessage(req, null, data));
                            redisClient.SET(key, JSON.stringify(data));
                            redisClient.EXPIRE(key, 300);
                        }
                    })
                }
            });
        }
    });
};

exports.homePageBanner = function (req, res) {
    var token = req.params.token;

    userService.homePageBannerService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get homePageBanner' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1014))
        } else {
            var data = {
                banner: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 1014));
        }
    })
};

exports.homePageFreshNews = function (req, res) {
    var token = req.params.token;

    userService.homePageFreshNewsService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get homePageFreshNewsService' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1015))
        } else {
            var data = {
                freshNews: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 1015));
        }
    })
};

exports.homePageQuestionAndActivity = function (req, res) {
    var token = req.params.token;

    userService.homePageQuestionAndActivityService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get homePageQuestionAndActivity' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1016))
        } else {
            var data = {
                questions: result[0],
                activities: result[1]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 1016));
        }
    })
};

exports.homePageTopics = function (req, res) {
    var token = req.params.token;

    userService.homePageTopicsService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get homePageTopics' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1017))
        } else {
            var data = {
                topics: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 1017));
        }
    })
};

exports.userSignIn = function (req, res) {
    var token = req.params.token;

    userService.userSignInService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get userSignIn' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1018))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, {signInValue: signInValue, isSignIn: true}, 1018));


            //var input = {
            //    userId: token + '',
            //    scoreAddCount: signInValue,
            //    scoreAddRason: '签到'
            //};
            //
            //input.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';
            //
            //scoreProxy.invoke('addScoreManual', [input], function (err, result) {
            //    if (err) {
            //        logger.error('Exception happened when addScoreManual ...!' + err.message);
            //    } else {
            //        var data = JSON.parse(decodeURIComponent(result));
            //        logger.info(data);
            //    }
            //});


            toolUtil.hessianManualAddScore(token, 18, signInValue, '签到', function (err, result) {

            });
        }
    })
};

//随便逛逛
exports.randomSetCommunity = function (req, res) {
    var token = req.params.token;

    userService.randomSetCommunityService(token, function (err, result) {
        toolUtil.setUserByToken(token);
        res.json(messageUtil.composeSucceededMessage(req, null, result, 1019));
    })
};


exports.getUserQuestionStatistics = function (req, res) {
    var token = req.params.token;
    var userId = req.params.userId;

    userService.getUserQuestionStatisticsService(token, userId, function (err, result) {
        if (err) {
            logger.error('Exception happened when getUserQuestionStatistics ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {

            var data = {
                "questionCount": result[0],
                "replyCount": result[1],
                "adoptRate": result[2],
                "praised": result[3]
            };
            if (token != userId) {
                data.replyCount = 0;
            }
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

/**
 * 个人页数字1.6.0
 * @param req
 * @param res
 */
exports.getMyAppStatistics = function (req, res) {
    var token = req.params.token;
    var vcode = req.query.vcode;

    userService.getMyAppStatisticsService(token, Number(vcode), function (err, result) {
        if (err) {
            logger.error('Exception happened when getMyAppStatistics' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1020))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 1020))
        }
    })
};

exports.getFollowupUsers = function (req, res) {
    var token = req.params.token;

    userService.getFollowupUsersService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when getFollowupUsers ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1021));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 1021));
        }
    });
};

/**
 * 用户认证
 * @param req
 * @param res
 */
exports.authenticateUser = function (req, res) {
    var token = req.params.token;
    var invitationCode = req.body.invitationCode;
    var deviceId = req.params.deviceId;

    var lang = req.cparams.lang;
    var errorMsg = 'Request is being processed.';
    if (!lang)
        errorMsg = '已提交资料，请等待审核';

    if (invitationCode != null && invitationCode != '') {
        userService.validateInvitationCodeService(token, invitationCode, function (err, user) {
            if (err) {
                logger.error('Exception happened when authenticateUser ...!' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message));
            } else {
                userService.authenticateUserService(token, req, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when authenticateUser ...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, errorMsg, null));


                        //绑定邀请关系
                        userService.bindInvitationCodeService(token, user, invitationCode, deviceId);
                    }
                });
            }
        })
    } else {
        userService.authenticateUserService(token, req, function (err, result) {
            if (err) {
                logger.error('Exception happened when authenticateUser ...!' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, errorMsg, null));
            }
        });
    }
};

exports.authenticateUserByPromotionCode = function (req, res) {
    var code = req.body.code;
    var token = req.params.token;
    var invitationCode;

    if (invitationCode != null && invitationCode != '') {
        userService.validateInvitationCodeService(token, invitationCode, function (err, user) {
            if (err) {
                logger.error('Exception happened when authenticateUserByPromotionCode ...!' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message, 1022));
            } else {
                userService.authenticateUserByPromotionCodeService(code, token, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when authenticateUserByPromotionCode' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 1022));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, result[3], 1022));
                        exports.authenticationAddScore(token, result[4]);

                        //绑定邀请关系
                        userService.bindInvitationCodeService(token, user);

                        //邀请人加分
                        mysqlUtil.generateUserVoucher(user._id, 2, token, function (err, result) {
                            if (err) logger.error(err.message);
                        });
                    }
                })
            }
        });
    } else {
        userService.authenticateUserByPromotionCodeService(code, token, function (err, result) {
            if (err) {
                logger.error('Exception happened when authenticateUserByPromotionCode' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message, 1022));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, result[3], 1022));

                exports.authenticationAddScore(token, result[4]);

                //if (result[0] != null) {
                //    //TODO 邀请通知
                //
                //
                //    var message = {
                //        msgType: 'invite',
                //        userId: result[0],
                //        inviteUserId: token
                //    };
                //    toolUtil.putMessageBusinessMQ(message);
                //
                //    //建立相互关注
                //    userService.eachOtherFollowupService(token, result[0]);
                //}
            }
        })
    }
};

exports.getUserAuthenticationStatus = function (req, res) {
    var token = req.params.token;
    userService.getUserAuthenticationStatusService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when getUserAuthenticationStatusService ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1023));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 1023));
        }
    });
};


exports.authenticationAddScore = function (token, communityId) {


    inviteRecord.findOne({
        user: token + '',
        source: 1
    }, function (err, invite) {
        if (invite != null) {
            logger.error('已有情值奖励，无法重复增加奖励')
        } else {
            var input = {
                userId: token + '',
                userRole: 1,
                addScore: V_SCORE,
                addScoreReason: 'V认证成功',
                userActionType: 1
            };

            input.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';

            scoreProxy.invoke('addScore', [input], function (err, result) {
                if (err) {
                    logger.error('Exception happened when addScoreManual ...!' + err.message);
                } else {
                    var data = JSON.parse(decodeURIComponent(result));
                    logger.info(data);
                    if (data.status == 0) {
                        var temp = new inviteRecord();
                        temp.user = token + '';
                        temp.source = 1;
                        temp.score = input.scoreAddCount;
                        temp.reason = input.scoreAddRason;
                        temp.save();

                    }
                }
            });
        }
    });


    //userDevice.findOne({userId: token}, 'vCode', function (err, version) {
    //    if ((version != null && version.vCode != null && version.vCode < 1403) || enbaleVoucher == 'No') {
    //        var arg = {
    //            userId: token,
    //            userRole: 1,
    //            addScore: 20,
    //            userActionType: 1
    //        };
    //
    //        arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';
    //
    //        scoreProxy.invoke('addScore', [arg], function (err, reply) {
    //            try {
    //                var data = JSON.parse(decodeURIComponent(reply));
    //                if (err) {
    //                    logger.error('hessianInvokeAddScore-----' + err.message);
    //                } else if (data.status != 0) {
    //                    logger.error('hessianInvokeAddScore----' + data.status + '----' + data.msg);
    //                }
    //            } catch (e) {
    //                logger.error('hessianInvokeAddScore---' + e);
    //            }
    //        });
    //    } else {
    //        Users.findOne({_id: token}, function (err, user) {
    //            if (user == null || user.community == null) {
    //                logger.error('无效用户')
    //            } else {
    //                mysqlUtil.query('select * from voucher_user_bind where user_id=? and reward_source=1', [user._id + ''], function (err, result) {
    //                    if (err || result.length > 0) {
    //                        if (err)logger.error(err.message);
    //                        logger.error('无法重复增加奖励')
    //                    } else {
    //
    //                        inviteRecord.findOne({
    //                            user: user._id + '',
    //                            source: 1
    //                        }, function (err, invite) {
    //                            if (invite != null) {
    //                                logger.error('已有情值奖励，无法重复增加奖励')
    //                            } else {
    //                                var community = communityId + '';
    //                                var nowDate = new Date().getTime();
    //                                var sql = 'select voucher_type_id,reward_expiredate_length,type,voucher_val,community_name from voucher_reward_rule r,voucher_type t where r.from_time<? and r.to_time>? and r.reward_source=? and r.community_id=? and t.id=r.voucher_type_id';
    //                                mysqlUtil.query(sql, [nowDate, nowDate, 1, community], function (err, result) {
    //                                    if (err || result.length == 0) {
    //                                        logger.error(err ? err : '无奖励规则');
    //                                    } else {
    //                                        if (result[0].type == 1) {
    //                                            mysqlUtil.getCardNumber(function (number) {
    //                                                var cardNo = moment().format('YYMMDD') + number;
    //                                                var expire = moment(nowDate).endOf('day').toDate().getTime() + result[0].reward_expiredate_length * 24 * 60 * 60 * 1000;
    //                                                var data = {
    //                                                    user_id: user._id + '',
    //                                                    expire_time: expire,
    //                                                    voucher_type_id: result[0].voucher_type_id,
    //                                                    is_use: 0,
    //                                                    reward_source: 1,
    //                                                    card_no: cardNo,
    //                                                    community_name: result[0].community_name,
    //                                                    create_time: new Date().getTime()
    //                                                };
    //                                                mysqlUtil.query('insert into voucher_user_bind set?', data, function (err, result) {
    //                                                    if (err) {
    //                                                        logger.error(err);
    //                                                    } else {
    //                                                        var content = {
    //                                                            type: 1,
    //                                                            flag: 2,
    //                                                            openType: 8,
    //                                                            contentId: user._id,
    //                                                            desc: '恭喜您！您获得了一张代金券'
    //                                                        };
    //                                                        var pushData = {
    //                                                            uList: [user._id],
    //                                                            content: content,
    //                                                            tag: '福利券',
    //                                                            type: 'operate'
    //                                                        };
    //                                                        toolUtil.putMessageGetuiPushMQ(pushData);
    //                                                    }
    //                                                })
    //                                            });
    //                                        } else if (result[0].type == 2) {
    //                                            var input = {
    //                                                userId: user._id + '',
    //                                                userRole: 1,
    //                                                addScore: result[0].voucher_val,
    //                                                addScoreReason: 'V认证',
    //                                                userActionType: 1
    //                                            };
    //
    //                                            logger.info(input);
    //
    //                                            input.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';
    //
    //                                            scoreProxy.invoke('addScore', [input], function (err, result) {
    //                                                if (err) {
    //                                                    logger.error('Exception happened when addScoreManual ...!' + err.message);
    //                                                } else {
    //                                                    var data = JSON.parse(decodeURIComponent(result));
    //                                                    logger.info(data);
    //                                                    if (data.status == 0) {
    //                                                        var temp = new inviteRecord();
    //                                                        temp.user = user._id + '';
    //                                                        temp.source = 1;
    //                                                        temp.score = input.scoreAddCount;
    //                                                        temp.reason = input.scoreAddRason;
    //                                                        temp.save();
    //
    //                                                    }
    //                                                }
    //                                            });
    //                                        }
    //                                    }
    //                                });
    //                            }
    //                        });
    //                    }
    //                });
    //            }
    //        })
    //    }
    //});
};

exports.getUserInvitedCode = function (req, res) {
    var token = req.params.token;

    userService.getUserInvitedCodeService(token, function (err, result) {
        var data = {
            invitedCode: result,
            invitedAuth: 0
        };
        res.json(messageUtil.composeSucceededMessage(req, null, data))
    });
};


exports.getMyVoucherList = function (req, res) {
    var token = req.params.token;

    userService.getMyVoucherListService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when getMyVoucherList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1024));
        } else {

            var data = {
                voucherList: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 1024));
        }
    })
};

exports.getVoucherDetail = function (req, res) {
    var voucherId = req.params.voucherId;
    var token = req.params.token;

    userService.getVoucherDetailService(Number(voucherId), token, function (err, result) {
        if (err) {
            logger.error('Exception happened when getVoucherDetail ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1025));
        } else {
            var data = {
                voucher: result[0],
                retailerList: result[1]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 1025));
        }
    })
};

//=================================================== Web后台管理 ============================================

//根据查询条件，页码显示用户
exports.findByNameORPhone = function (req, res) {
    var pageNo = req.params.pageNo;
    var input = req.body;

    userService.findByNameORPhoneService(pageNo, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when apply to be expert ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, ''));
        } else {
            if (result == null) {
                res.json(messageUtil.composeFailedMessage(req, '没有用户'));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, result));
            }
        }
    })
};

//根据页码显示全部用户
exports.getAllUser = function (req, res) {
    var pageNo = req.params.pageNo;

    userService.getAllUserService(pageNo, function (err, result) {
        if (err) {
            logger.error('Exception happened when apply to be expert ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, ''));
        } else {
            if (result == null) {
                res.json(messageUtil.composeFailedMessage(req, '没有用户'));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, result));
            }
        }
    })
};

/**
 * 后台注册用户
 */
exports.registerUserFromBackOffice = function (req, res) {
    var input = req.body;
    var errorMsg = '';
    var successMsg = '';
    for (var i = 0; i < input.length; i++) {
        if ((input[i].userName != null || input[i].email != null || input[i].mobilePhone != null) && input[i].userPassword != null) {
            userService.registerUserFromBackOfficeService(input[i], function (err, user) {
                if (err) {
                    logger.error("Failed to register this user - " + err.message);
                    errorMsg = errorMsg + JSON.stringify(input[i]) + ',';
                } else {
                    logger.debug("Succeeded to register a user! - " + user._id);
                    //获取token并缓冲
                    logger.info(user._id);
                    var token = toolUtil.generateAndCacheToken(user._id);
                    //返回消息
                    var registerUserData = {
                        "_id": user._id,
                        "huanxinUserName": user.huanxinUserName,
                        "token": token
                    };
                    //userService.sendWelcomeNewsService(input.mobilePhone, function (err, result) {
                    //    if (err) {
                    //        logger.error('failed to send welcome news' + err.message);
                    //    }
                    //});
                    successMsg = successMsg + JSON.stringify(input[i]) + ',';
                }
                if (i == input.length - 1) {
                    //fix me : 应该在全部添加完成时回调方法里面加
                    logger(errorMsg + '  ' + successMsg);
                    res.json(messageUtil.composeSucceededMessage(req, errorMsg + '创建失败\n' + successMsg + '创建成功', null));
                }
            });
        }
        else {
            logger.error("Failed to register user ! - You have to provide at least userID/email/mobilePhone and also password for registration...!");
            errorMsg = errorMsg + JSON.stringify(input[i]) + ',';
            if (i == input.length - 1) {
                //fix me : 应该在全部添加完成时回调方法里面加
                res.json(messageUtil.composeSucceededMessage(req, errorMsg + '创建失败\n' + successMsg + '创建成功', null));
            }
        }
    }
};


/**
 * user-controller.js
 *搜索用户
 *author：chenjinzhuan
 * */
exports.searchBackOfficeUser = function (req, res) {
    //var pageNo = req.params.pageNo;
    var input = req.body;

    userService.searchBackOfficeUserService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when apply to be expert ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, ''));
        } else {
            if (result == null) {
                res.json(messageUtil.composeFailedMessage(req, '没有用户'));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, result));
            }
        }
    })
};

/**
 * user-controller.js
 * 登录验证
 *author：chenjinzhuan
 * */
exports.adminLogin = function (req, res) {
    var input = req.body;

    userService.adminLoginService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when login ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when login ...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.getAuthenticationUserList = function (req, res) {
    var communityId = req.params.communityId;
    var status = req.params.status;
    var nickname = req.params.nickname;
    var page = req.params.page;

    userService.getAuthenticationUserListService(communityId, status, nickname, page, function (err, result) {
        if (err) {
            logger.error('Exception happened when getAuthenticationUserList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getAuthenticationUserList ...!' + err.message));
        } else {
            var data = {
                uList: result[0],
                totalPage: Math.ceil(result[1] / 20)
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

/**
 * 审核用户认证
 * @param req
 * @param res
 */
exports.examineUserAuthenticate = function (req, res) {
    var body = req.body;

    userService.examineUserAuthenticateService(body, function (err, result) {
        if (err) {
            logger.error('Exception happened when examineUserAuthenticate ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
            if (body.status) {
                exports.authenticationAddScore(body.user, body.community);

                if (result[1] != null) {
                    mysqlUtil.generateUserVoucher(result[1], 2, body.user, function (err, result) {
                        if (err) logger.error(err.message);
                    });
                }
            }
        }
    })


};

exports.refuseUserAuthenticate = function (req, res) {
    var id = req.params.id;
    var body = req.body;

    userService.refuseUserAuthenticateService(id, body, function (err, result) {
        if (err) {
            logger.error('Exception happened when refuseUserAuthenticate ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when refuseUserAuthenticate ...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.generateVoucher = function (req, res) {
    var userId = req.params.userId;

    mysqlUtil.generateUserVoucher(userId, 2, '549968e5bc537bb017000a04', function (err, result) {
        if (err) {
            logger.error(err);
        }
        res.json({message: 1})
    })
};

exports.getRecentContactPerson = function (req, res) {
    var token = req.params.token;

    userService.getRecentContactPersonService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when getRecentContactPerson ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1026));
        } else {
            var data = {
                count: result.length,
                users: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 1026));
        }
    })
};

exports.getScoreRank = function (req, res) {
    var pageNo = req.params.pageNo;
    var token = req.params.token;

    userService.getScoreRank(token, pageNo, function (err, result) {
        if (err) {
            logger.error('Exception happened when getScoreRank ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1027));
        } else {
            var data = {
                rankList: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 1027));
        }
    })
};

/**
 * 重置密码1.6.0
 * @param req
 * @param res
 */
exports.resetUserPassword = function (req, res) {
    var input = req.body;
    var lang = req.cparams.lang;

    if (input.mobilePhone != null && input.verificationCode != null) {
        cacheUtil.cacheGet(input.mobilePhone, function (err, result) {
            if (result != null && result == input.verificationCode) {
                userService.resetUserPasswordService(input, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when resetUserPassword' + err.message);
                        res.json(messageUtil.composeErrorMessage(req, err, 1028))
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null, 1028));
                    }
                })
            } else {
                logger.error("Failed to check code ! - invalid verification code!");
                var errorMsg = 'Invalid verification code';
                if (!lang)
                    errorMsg = '验证码错误';

                res.json(messageUtil.composeFailedMessage(req, errorMsg, 1028));
            }
        });
    } else {
        logger.error("Exception happened when resetUserPassword--信息不全");
        var errorMsg = 'Incomplete information, failed to reset password';
        if (!lang)
            errorMsg = '信息不完整，无法重置密码';

        res.json(messageUtil.composeFailedMessage(req, errorMsg, 1028));
    }
};

/**
 * 获取我关注人列表1.6.0
 * @param req
 * @param res
 */
exports.getMyFollowupUsers = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;

    userService.getMyFollowupUsersService(token, ts, function (err, result) {
        if (err) {
            logger.error('Exception happened when getMyFollowupUsers' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1021))
        } else {
            var data = {
                ts: result.length > 0 ? result[result.length - 1]._doc.followTime.getTime() : (new Date("2000/04/01 00:00:00")).getTime(),
                users: result
            };

            res.json(messageUtil.composeSucceededMessage(req, null, data, 1021));
        }
    })
};

/**
 * 获取我的被关注人列表1.6.0
 * @param req
 * @param res
 */
exports.getMyBeFollowedUsers = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;

    userService.getMyBeFollowedUsersService(token, ts, function (err, result) {
        if (err) {
            logger.error('Exception happened when getMyBeFollowedUsers' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1030))
        } else {
            var data = {
                ts: result.length > 0 ? result[result.length - 1]._doc.followTime.getTime() : (new Date("2000/04/01 00:00:00")).getTime(),
                users: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 1030));
        }
    })
};

/**
 * 我的未读消息数1.6.0
 * @param req
 * @param res
 */
exports.getMyUnreadMessageCount = function (req, res) {
    var token = req.params.token;

    userService.getMyUnreadMessageCountService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when getMyUnreadMessageCount' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1031))
        } else {
            /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
            var gagOrNot = "0";
            if(result[2]._doc.gagOrNot) {
                gagOrNot = "1";
            }
            var data = {
                neighbourUnRead: result[0],
                systemUnRead: result[1],
                gagOrNot:gagOrNot
            };
            /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */
            res.json(messageUtil.composeSucceededMessage(req, null, data, 1031));
        }
    })
};

/**
 * 其他用户首页1.6.0
 * @param req
 * @param res
 */
exports.otherUserPage = function (req, res) {
    var userId = req.params.userId;
    var token = req.params.token;
    var vCode = req.cparams.vcode;

    userService.otherUserPageService(userId, token, vCode, function (err, result) {
        if (err) {
            logger.error('Exception happened when get otherUserPage' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1032))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 1032))
        }
    })
};

exports.otherUserPageNew = function (req, res) {
    var userId = req.params.userId;
    var token = req.params.token;
    var communityId = req.query.communityId;

    userService.otherUserPageNewService(userId, token, communityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when get otherUserPageNew' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1032))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 1032))
        }
    })
};

/**
 * 其他用户档案1.6.0
 * @param req
 * @param res
 */
exports.otherUserProfile = function (req, res) {
    var userId = req.params.userId;
    var token = req.params.token;

    userService.otherUserProfileService(userId, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get otherUserProfile' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1033))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 1033))
        }
    })
};

/**
 * 1.7.0 上传用户头像
 * @param req
 * @param res
 */
exports.uploadUserImage = function (req, res) {

    var token = req.params.token;
    var input = req.body;
    var lang = req.cparams.lang;

    if (input.images == null) {
        logger.error('Failed to upload user image --- 头像资料为null');
        var errorMsg = 'Failed to upload photo';
        if (!lang)
            errorMsg = '上传头像失败';

        res.json(messageUtil.composeFailedMessage(req, errorMsg, 1034))
    } else {
        userService.setImagesToUser(token, input.images, function (err, result) {
            if (err || input == null) {
                res.json(messageUtil.composeFailedMessage(req, 'Failed to upload user profile Images... - ' + err.message, 1034));
            } else {
                toolUtil.setUserByToken(token);
                res.json(messageUtil.composeSucceededMessage(req, null, input, 1034));
            }
        });
    }
};

/**
 * 1.7.0 用户提交认证资料
 * @param req
 * @param res
 */
exports.postUserAuthenticationData = function (req, res) {
    var token = req.params.token;
    var input = req.body;
    var invitationCode = req.body.invitationCode;
    var deviceId = req.params.deviceId;

    var lang = req.cparams.lang;
    var errorMsg = 'Request is being processed.';
    if (!lang)
        errorMsg = '已提交资料，请等待审核';

    input.imageURL = '/' + input.imageURL;

    if (invitationCode != null && invitationCode != '') {
        userService.validateInvitationCodeService(token, invitationCode, function (err, user) {
            if (err) {
                logger.error('Exception happened when authenticateUser ...!' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message, 1035));
            } else {
                userService.postUserAuthenticationDataService(token, input, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when authenticateUser ...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 1035));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, errorMsg, null, 1035));
                        //绑定邀请关系
                        userService.bindInvitationCodeService(token, user, invitationCode, deviceId);
                    }
                });
            }
        })
    } else {
        userService.postUserAuthenticationDataService(token, input, function (err, result) {
            if (err) {
                logger.error('Exception happened when authenticateUser ...!' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message, 1035));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, errorMsg, null, 1035));
            }
        });
    }
};

exports.getWantDoSomethingList = function (req, res) {
    var token = req.params.token;

    userService.getWantDoSomethingListService(token, function (err, result) {
        res.json(messageUtil.composeSucceededMessage(req, null, result, 1036))
    })
};

exports.postUserWant = function (req, res) {
    var token = req.params.token;
    var input = req.body;

    userService.postUserWantService(token, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when postUserWant ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1037));
        } else {
            var data = {
                ts: result[0].uList.length > 0 ? result[0].uList[result[0].uList.length - 1].dateCreated.getTime() : (new Date("2000/04/01 00:00:00")).getTime(),
                uList: result[0].uList,
                count: result[0].count + 1,
                key: result[1].key
            };

            if (input.type == 1) {
                data.birthday = (moment().diff(moment(input.birthday), 'years') + 1) + '岁'
            }

            if (result[1].ugc != null) {
                data.ugc = result[1].ugc;

                if (data.ugc.createdBy.roomUnit != null && data.ugc.createdBy.roomUnit != '')
                    data.ugc.createdBy._doc.roomUnit = !isNaN(data.ugc.createdBy.roomUnit) ? data.ugc.createdBy.roomUnit + '单元' : data.ugc.createdBy.roomUnit;

                if (data.ugc.createdBy.showUnit != null && !data.ugc.createdBy.showUnit) {
                    data.ugc.createdBy.roomUnit = undefined;
                }
                data.ugc.createdBy.showUnit = undefined;
            }

            if (result[3] != null) {
                data.tag = result[3]
            }

            res.json(messageUtil.composeSucceededMessage(req, null, data, 1037));

            if (result[2]) {
                userService.buildPushParamsMapService(input, function (err, map) {
                    var message = {
                        msgType: 'iwant',
                        moudle: input.type,
                        contentId: map._id + '',
                        contentType: 'enjoy',
                        mapId: map._id + '',
                        userId: token,
                        community: result[0].community
                    };
                    if (input.type != 1) {
                        message.condition = result[0].opt.condition
                    }

                    //推送
                    toolUtil.putMessageBusinessMQ(message);
                });
            }
        }
    })
};

exports.getSameWantUserList = function (req, res) {
    var token = req.params.token;
    var input = req.body;
    var page = req.params.ts;

    userService.getSameWantUserListService(token, page, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when getSameWantUserList ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1038))
        } else {
            var data = {
                ts: result.length > 0 ? result[result.length - 1].dateCreated.getTime() : (new Date("2000/04/01 00:00:00")).getTime(),
                uList: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 1038));
        }
    })
};

exports.getWantRecommendUgc = function (req, res) {
    var token = req.params.token;
    var input = req.body;

    userService.getWantRecommendUgcService(token, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when getWantRecommendUgc ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 1039))
        } else {

            if (result != null) {
                if (result.createdBy.roomUnit != null && result.createdBy.roomUnit != '')
                    result.createdBy._doc.roomUnit = !isNaN(result.createdBy.roomUnit) ? result.createdBy.roomUnit + '单元' : result.createdBy.roomUnit;

                if (result.createdBy.showUnit != null && !result.createdBy.showUnit) {
                    result.createdBy.roomUnit = undefined;
                }
                result.createdBy.showUnit = undefined;
            }
            res.json(messageUtil.composeSucceededMessage(req, null, result, 1039));
        }
    })
};

exports.getUserWantPage = function (req, res) {
    var mapId = req.params.mapId;
    var token = req.params.token;

    userService.getUserWantPageService(token, mapId, function (err, result) {
        if (err) {
            logger.error('Exception happened when getWantRecommendUgc ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1040))
        } else {
            var data = {
                ts: result[0].uList.length > 0 ? result[0].uList[result[0].uList.length - 1].dateCreated.getTime() : (new Date("2000/04/01 00:00:00")).getTime(),
                uList: result[0].uList,
                count: result[0].count,
                key: result[1].key,
                body: result[0].opt
            };

            if (result[0].opt.type == 1) {
                data.birthday = (moment().diff(moment(result[0].opt.birthday), 'years') + 1) + '岁'
            }

            if (result[1].ugc != null) {
                data.ugc = result[1].ugc;

                if (data.ugc.createdBy.roomUnit != null && data.ugc.createdBy.roomUnit != '')
                    data.ugc.createdBy._doc.roomUnit = !isNaN(data.ugc.createdBy.roomUnit) ? data.ugc.createdBy.roomUnit + '单元' : data.ugc.createdBy.roomUnit;

                if (data.ugc.createdBy.showUnit != null && !data.ugc.createdBy.showUnit) {
                    data.ugc.createdBy.roomUnit = undefined;
                }
                data.ugc.createdBy.showUnit = undefined;
            }

            if (result[2] != null) {
                data.tag = result[2]
            }

            res.json(messageUtil.composeSucceededMessage(req, null, data, 1040));
        }
    })
};

/*  宝宝树66小区五期   add  重置申请状态 guo.xiaomin  20171207   start   */
exports.resetApplyStatus = function (req, res) {
    var token = req.params.token;
    userService.resetApplyStatus(token, function (err, result) {
        if (err) {
            logger.error('Failed to resetApplyStatus ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 2001))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 2001))
        }
    })
};
/*  宝宝树66小区五期   add  重置申请状态 guo.xiaomin  20171207   end   */